package com.demo.swingquickticket.service;

import com.demo.swingquickticket.entity.Station;
import com.demo.swingquickticket.util.HttpClientUtil;
import com.demo.swingquickticket.util.HttpInfo;
import com.demo.swingquickticket.util.http.*;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StationService {

    public Map<String, List<Station>> initStationList() {
        Map<String, List<Station>> stationMap = new HashMap<>();
        StringBuilder url = new StringBuilder("https://www.12306.cn/index/");
        HttpInfo indexInfo = HttpClientUtil.getForString(url.toString(), null, null, null, "utf-8");
        Document index = Jsoup.parse(indexInfo.getResult());
        Elements elements = index.select("script[src]");
        for (Element temp : elements) {
            if (temp.attr("src").contains("station_name")) {
                url.append(temp.attr("src"));
                HttpInfo station = HttpClientUtil.getForString(url.toString(), null, null, null, "utf-8");
                String stationStr = station.getResult();
                stationStr = stationStr.substring(stationStr.indexOf("'") + 2, stationStr.lastIndexOf("'"));
                System.out.println(stationStr);
                return Station.addStations(stationStr);
            }
        }
        return stationMap;
    }

}
